import React, { useEffect, useState , Key} from "react";
import { useNavigate } from "react-router-dom";
import { Button, Card, Form, Input, Table ,message , Tooltip} from "antd";
import {
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import style from "./index.module.css";
import  { getHosSetListRequest , deleteHosListRequest , batchDeleteRequest} from "@/api/hospital/hospitalSet";
import { getHosSetListRecordsType ,getHosSetListItemsType } from "@/api/hospital/model/hospitalSetTypes";
import type {searchListType} from "./type"

export default function HospitalSet() {
  const naviGate = useNavigate()
  // loading控制 table 是否加载中
  const [loading, setLoading] = useState(false);
  // hospitalList 后端请求回来的数据 重新覆盖的值；
  const [hospitalList, setHospitalList] = useState<getHosSetListRecordsType>(
    []
  );
  // 定义 current 页码
  const [current, setCurrent] = useState(1);
  // 定义 total 总条数
  const [total, setTotal] = useState(0);
  // 定义 pageSize 每页条数
  const [pageSize, setPageSize] = useState(3);
  // 定义 模糊搜索
  const [fieldsValue , setFieldsValue] = useState<searchListType>({})
  // 删完之后重新渲染
  const [deleteRender , setDeleteRender] = useState(false)
  // 控制批量删除是否显示
  const [isShow , setIsShow] = useState(true)
  // 接收批量删除的Ids
  const [batchDeleteIds , setBatchDeleteIds] = useState<Key[]>([])
  useEffect(() => {
    //在请求开始之前,设置 loading 为true
    setLoading(true);
    const getHosSetList = async () => {
      const re = await getHosSetListRequest({
        page: current,
        limit: pageSize,
        ...fieldsValue
      });
      setHospitalList(re.records);
      // 获取定义 total 总条数
      setTotal(re.total);
      // 请求完成后要把 loading 修改为false
      setLoading(false);
    };
    getHosSetList();
  }, [current, pageSize,fieldsValue,deleteRender]);

  // 页码点击事件
  const getHospitalList = (current: number, pageSize: number) => {
    //参数1page:当前点击的页码  参数2 pageSize:每页条数
    //点击以后给state设置page和pageSize的值
    setCurrent(current);
    setPageSize(pageSize);
  };

  // 模糊搜索事件
  const searchList = (FieldsValue:searchListType) => {
    setCurrent(current)
    setFieldsValue(FieldsValue)
  }
  const addHosHandle = () => {
    naviGate("/syt/hospital/hospitalSet/addHosSet")
  }

  // 删除数据

  const deleteHosData = (id:number) => {
    return async () => {
      deleteHosListRequest(id)
      // 删除数据后重新渲染
      setDeleteRender(!deleteRender)

      message.success('删除医院成功')
    }
   
  }

  // 批量删除回调
  const  batchDeleteHosHandle = async () => {
    await batchDeleteRequest(batchDeleteIds);
    // 删除数据后重新渲染
    setDeleteRender(!deleteRender)

    message.success('删除医院成功')
    
    // 删完改变批量删除是否显示
    setIsShow(true)
  }

  const columns = [
    {
      title: "序号",
      width: 60,
      dataIndex: "name",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "医院编号",
      dataIndex: "hoscode",
    },
    {
      title: "api基础路径",
      dataIndex: "apiUrl",
    },
    {
      title: "签名",
      dataIndex: "signKey",
    },
    {
      title: "联系人姓名",
      dataIndex: "contactsName",
    },
    {
      title: "联系人手机",
      dataIndex: "contactsPhone",
    },
    {
      title: "操作",
      dataIndex: "name",
      width: 130,
      fixed: "right" as "right",
      render(_:any , data:getHosSetListItemsType) {
        const {id} = data
        return (
          <div>
            <Tooltip title = "修改医院">
            <Button
              type="primary"
              icon={<EditOutlined />}
              className={style.hospR}
              //点击修改的时候跳转复用组件
              onClick = {() => {naviGate(`/syt/hospital/hospitalSet/updateHosSet/${id}`)}}
            ></Button>
            </Tooltip>
            <Tooltip title = '删除医院'>
            <Button type="primary" danger icon={<DeleteOutlined />} onClick = {deleteHosData(id)}></Button>
            </Tooltip>
          </div>
        );
      },
    },
  ];

  return (
    <div className={style.outer}>
      <Card>
        <Form name="basic" wrapperCol={{ span: 30 }} layout="inline" onFinish={searchList}>
          <Form.Item
            name="hosname"
            // rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input placeholder="医院名称" />
          </Form.Item>

          <Form.Item
            name="hoscode"
            // rules={[{ required: true, message: "Please input your password!" }]}
          >
            <Input placeholder="医院编号" />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="default" htmlType="reset">
              清空
            </Button>
          </Form.Item>
        </Form>
        <div className={style.hospL}>
          <Button type="primary" className={style.hospR} onClick={addHosHandle} >
            添加
          </Button>
          <Button type="primary" danger disabled = {isShow} onClick = {batchDeleteHosHandle}>
            批量删除
          </Button>
        </div>
        <Table
          className={style.hospL}
          // 决定表格渲染几列
          columns={columns}
          // 决定表格每一行渲染什么数据
          dataSource={hospitalList}
          // 滚动条
          scroll={{ x: 1300 }}
          // 设置边框
          bordered
          // 遍历的key属性的值用id
          rowKey="id"
          // 设置多选框
          rowSelection={{
            onChange(ids: Key[]) {
              //点击的时候改变批量删除是否显示
              setIsShow(!ids.length)
              //接收批量删除的Ids
              setBatchDeleteIds(ids)
            }
          }}
          // 分页器设置
          pagination={{
            // 页码的配置：当前页码
            current,
            // 总数据的数量
            total,
            // 每页条数
            pageSize,
            // 展示更改每页条数的选项
            pageSizeOptions: [2, 3, 4, 5],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,
            showTotal(total) {
              return `数据的总条数${total}`;
            },
            onChange: getHospitalList,
            onShowSizeChange: getHospitalList,
           
          }}
          loading={loading}
        />
      </Card>
    </div>
  );
}
